package no.rodland.acc.model;

import org.joda.time.DateTime;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

import no.rodland.acc.db.AbstractRow;

/**
 * Created by IntelliJ IDEA.
 *
 * @Since: Jun 18, 2010 12:04:38 PM
 * @Author: fmr
 */
public class BudgetAccount extends AbstractRow {
    protected String name;
    private AccountGroup mainGroup;

    protected BudgetAccount(ResultSet rs, Map<Integer, AccountGroup> accountGroups) throws SQLException {
        super(rs.getInt("id"),
                new DateTime(rs.getTimestamp("updated_date")),
                new DateTime(rs.getTimestamp("created_date")));
        setName(rs.getString("name"));
        if (accountGroups != null) {
            mainGroup = accountGroups.get(rs.getInt("main_group_id"));
        }
    }

    @Override
    public String getTableName() {
        return "budget_accounts";
    }

    @Override
    public Object[] getData() {
        return new Object[]{getName(), getMainGroup().getId()};
    }

    @Override
    public String[] getColumns() {
        return new String[]{"name", "main_group_id"};
    }

    public String getName() {
        return name;
    }

    @Override
    public String getText() {
        return getName();
    }

    public AccountGroup getMainGroup() {
        return mainGroup;
    }

    @Override
    public boolean usesIdentity() {
        return false;
    }

    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("BudgetAccount");
        sb.append("{name='").append(name).append('\'');
        sb.append(", mainGroup=").append(mainGroup);
        sb.append('}');
        return sb.toString();
    }

    public void setName(String name) {
        this.name = name;
    }

    @SuppressWarnings({"RedundantIfStatement"})
    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        BudgetAccount that = (BudgetAccount) o;

        if (getId() != that.getId()) {
            return false;
        }
        if (mainGroup != null ? !mainGroup.equals(that.mainGroup) : that.mainGroup != null) {
            return false;
        }
        if (name != null ? !name.equals(that.name) : that.name != null) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + (mainGroup != null ? mainGroup.hashCode() : 0);
        result = 31 * result + getId();
        return result;
    }
}
